
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
#include <cstdlib>

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
  public:
    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
        ListNode *resultHead = new ListNode(0);
        ListNode *pointer = resultHead;
        int carry = 0;
        int num = l1->val + l2->val;
        pointer->val = num % 10;
        carry = num / 10;
        while (l1->next != NULL && l2->next != NULL) {
            l1 = l1->next;
            l2 = l2->next;
            num = l1->val + l2->val + carry;
            pointer->next = new ListNode(0);
            pointer = pointer->next;
            pointer->val = num % 10;
            carry = num / 10;
        }
        while (l1->next != NULL) {
            l1 = l1->next;
            pointer->next = new ListNode(0);
            pointer = pointer->next;
            num = carry + l1->val;
            pointer->val = num % 10;
            carry = num / 10;
        }
        while (l2->next != NULL) {
            l2 = l2->next;
            pointer->next = new ListNode(0);
            pointer = pointer->next;
            num = carry + l2->val;
            pointer->val = num % 10;
            carry = num / 10;
        }
        if (carry) {
            pointer->next = new ListNode(1);
        }
        return resultHead;
    }
};